package com.hanxiaozhang.basicknowledgecode.serializeanddeserialize;

import java.io.*;
import java.text.MessageFormat;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2024/5/13
 * @since 1.0.0
 */
public class SerializeAndDeserializeTest {


    public static final String FILE_PATH = "D:/Person.txt";

    public static void main(String[] args) throws Exception {
        // 序列化Person对象
        serializePerson();
        // 反序列Person对象
        Person p = deserializePerson();
        System.out.println(MessageFormat.format("name={0},age={1},sex={2}", p.getName(), p.getAge(), p.getSex()));
    }


    /**
     * 序列化Person对象
     *
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void serializePerson() throws FileNotFoundException, IOException {
        Person person = new Person();
        person.setName("xiaohan");
        person.setAge(25);
        person.setSex("男");
        // ObjectOutputStream 对象输出流，将Person对象存储到E盘的Person.txt文件中，完成对Person对象的序列化操作
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
                new File(FILE_PATH)));
        oo.writeObject(person);
        System.out.println("Person对象序列化成功！");
        oo.close();
    }


    /**
     * 反序列Person对象
     *
     * @return
     * @throws Exception
     * @throws IOException
     */
    private static Person deserializePerson() throws Exception, IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                new File(FILE_PATH)));
        Person person = (Person) ois.readObject();
        System.out.println("Person对象反序列化成功！");
        return person;
    }
}

class Person implements Serializable {

    /**
     * 序列化ID
     */
    private static final long serialVersionUID = -5809782578272943999L;


    private int age;
    private String name;
    private String sex;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

